package com.hpq.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.hpq.websocket.domain.enums.WSReqTypeEnum;
import com.hpq.websocket.domain.vo.request.WSBaseReq;
import com.hpq.websocket.service.WebSocketService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private WebSocketService webSocketService;

    public void channelActive(ChannelHandlerContext ctx){
        webSocketService = SpringUtil.getBean(WebSocketService.class);
        webSocketService.connect(ctx.channel());
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx,Object evt) throws Exception {
       // 握手
        if(evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            this.webSocketService.connect(ctx.channel());
            log.info("握手成功");
            String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN);
            if(StrUtil.isNotBlank(token)){
                this.webSocketService.authorize(ctx.channel(), token);
                log.info("登录认证成功");
            }


        }else if(evt instanceof IdleStateEvent){
            //读空闲
            IdleStateEvent  event = (IdleStateEvent)evt;
            if(event.state() == IdleState.READER_IDLE){
                log.info("读空闲");
                //todo 用户下线
                //连接关闭
                userOffLine(ctx.channel());
                log.info("用户下线");
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * 处理通道连接断开事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        userOffLine(ctx.channel());
        log.info("webSocket连接关闭");
    }

    /**
     * 用户下线逻辑
     * @param channel
     */
    private void userOffLine(Channel channel){
        webSocketService.remove(channel);
        channel.close();
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        //
        WSBaseReq wsBaseReq = JSONUtil.toBean(text, WSBaseReq.class);

        switch (WSReqTypeEnum.of(wsBaseReq.getType())) {
            case LOGIN:
              log.info("请求二维码登录");
                webSocketService.handlerLoginReq(ctx.channel());
                break;
            case AUTHORIZE:
                break;
            case HEARTBEAT:
                break;
        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       log.error("exceptionCaught:", cause);
       super.exceptionCaught(ctx, cause);

    }
}
